package com.qiku.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.qiku.entity.User;
import com.qiku.enums.TokenException;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;

/**
 * 用于创建、校验、解析token的工具
 */
public class JWTUtil {
    //定义secret秘钥  自定义
    private static final String TOKEN_SECRET="iphone 14pro Max";
    //设置过期时间  15分钟
    private static final long EXPIRE_TIME = 15*60*1000;

    /**
     * 创建令牌   并设置过期时间
     * @param user
     * @return
     */
    public static String createToken(User user) {
        //获取过期时间         当前时间的毫秒数 + 过期时间毫秒数
        Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
        // 私钥  和  加密算法
        Algorithm algorithm = null;
        try {
            algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //设置头部信息
        HashMap<String, Object> header = new HashMap<>();
        header.put("typ","jwt");
        header.put("alg","HS256");
        return JWT.create().withHeader(header)
                .withClaim("nickName",user.getName())
                .withClaim("userid",user.getId())
                .withClaim("password",user.getPassword())
                .withClaim("portrait",user.getPortrait())
                .withExpiresAt(date)  //设置过期时间
                .sign(algorithm);  //加密

    }

    /**
     * 校验token是否正确
     * @param token
     * @return
     */
    public static int isVerify(String token){
        try{
            //根据HMAC256算法生成签名
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
        } catch (TokenExpiredException e){
            return TokenException.TOKEN_TIMEOUT_CDOE.getCode(); //Token 过期
        } catch (JWTDecodeException e){
            return TokenException.TOKEN_NULL_CODE.getCode(); //令牌格式错误！或为空令牌
        } catch (JWTVerificationException e){
            return TokenException.TOKEN_ERROR_CDOE.getCode(); //校验失败,token令牌就是错误的
        }catch (Exception e){
            e.printStackTrace();
        }
        return TokenException.TOKEN_SUCCESS_CODE.getCode();  //校验通过
    }

    /**
     * 解析id
     * @param token
     * @return
     */
    public static int pareTokenUserId(String token){
        DecodedJWT jwt = JWT.decode(token);
        int userid = jwt.getClaim("userid").asInt();
        return userid;
    }
    /**
     * 解析名字
     * @param token
     * @return
     */
    public static String pareTokenNickName(String token){
        DecodedJWT jwt = JWT.decode(token);
        String nickname = jwt.getClaim("nickName").asString();
        return nickname;
    }
    /**
     * 解析头像
     * @param token
     * @return
     */
    public static String pareTokenPortrait(String token){
        DecodedJWT jwt = JWT.decode(token);
        String portrait = jwt.getClaim("portrait").asString();
        return portrait;
    }

    /**
     * 解析密码
     * @param token
     * @return
     */
    public static String pareTokenPassword(String token){
        DecodedJWT jwt = JWT.decode(token);
        String password = jwt.getClaim("password").asString();
        return password;
    }



    public static void main(String[] args) {
        User user = new User();
        user.setId(1);
        user.setName("张三");
        user.setPassword("123444");
        user.setPortrait("www.baidu.com");
        String token = createToken(user);
        System.out.println(token);
//        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXNzd29yZCI6IjEyMzQ0NCIsIm5pY2tOYW1lIjoi5byg5LiJIiwicG9ydHJhaXQiOiJ3d3cucXEuIiwiZXhwIjoxNjYxMzI3MjU5LCJ1c2VyaWQiOjF9.2kbK9MSiHJm2KhARcToHIYWppgA-K6FR4mufiQDUA0E";
        System.out.println("token状态："+isVerify(token));
        System.out.println("userid："+pareTokenUserId(token));
        System.out.println("nickname："+pareTokenNickName(token));
        System.out.println("portrait："+pareTokenPortrait(token));
        System.out.println("password："+pareTokenPassword(token));

    }

}
